'use strict'

process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
const dbcfg = require('./dbconfig.js')
const pg = require('pg')
const wxkey = require('./wxkey.js')
const {httpcli} = require('gohttp')
const token = require('titbit-token')
const tbloader = require('titbit-loader')

try {
  fs.accessSync('./images')
} catch (err) {
  fs.mkdirSync('./images')
}

let psql = new pg.Pool(dbcfg)

let cert_path = '/usr/local/cert'

const app = new titbit({
  //开启调试模式，若有错误会输出错误信息。
  debug: true,
  globalLog: true,
  cert: `${cert_path}/www.vvh5.com.pem`,
  key: `${cert_path}/www.vvh5.com.key`
})

let tb = new tbloader();
tb.init(app);

app.addService('psql', psql);
app.addService('imagePath', `${__dirname}/images`);

let tok = new token({
  //token有效期，单位为秒
  expires: 45,
  //必须是32位字符
  key: '1qaz2wsx3edc4rfv5tgb6yhn7ujmki89',

  //必须是16位字符
  iv: '1q2w3e4r5t6y7u8i'
})

app.addService('tok', tok)

app.get('/mp-login/:code', async c => {
  let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
          + `?appid=${wxkey.appid}`
          + `&secret=${wxkey.secret}`
          + `&js_code=${c.param.code}`
          + `&grant_type=authorization_code`

  let ret = await httpcli.get(auth_url)
                        .then(res => {
                          return res.json()
                        })
  
  c.send( tok.make(ret) )
})

//运行在1234端口
app.run(1234)
